Skip to content

serve: reasoning as thinking blocks on the Messages API (and reasoning_content with tool calls) - #135

Open
PedroRossi wants to merge 3 commits into
RustingStudio:mainfrom
PedroRossi:pr/anthropic-thinking-blocks
Open

PedroRossi wants to merge 3 commits into
RustingStudio:mainfrom
PedroRossi:pr/anthropic-thinking-blocks

Conversation

@PedroRossi

@PedroRossi PedroRossi commented Nov 27, 2026 •

Copy link
Copy Markdown

Summary

Independent of #134 (no shared files).

With a thinking model (Qwen3.5/3.6 with thinking on, the server default), the reasoning reaches some API clients mixed
into the answer.

  1. /v1/messages (Anthropic Messages API, what Claude Code uses):
    • Whole replies came back as one text block holding everything the model generated: reasoning, a literal
      </think>, then the answer.
    • Streams sent every piece as text_deltas of block 0, the same mix.
    • Claude Code shows the reasoning and the tag in every reply, and sends them back as assistant text on the next turn.
  2. thinking: {"type": "disabled"}: was ignored, so the server default applied and a client could not turn thinking off.
  3. /v1/chat/completions replies that end in tool calls, not streamed: the text before the calls went to content
    as it was (reasoning and </think> included), with no reasoning_content.

/v1/chat/completions already split the reasoning everywhere else with chat::Think. This PR uses the same splitter
for the cases above. The block layout and the empty signature follow what llama.cpp's server sends, which Claude Code
accepts.

  • Whole Messages replies: a thinking block ("signature": ""; a local model has no signature to give), then the
    text block, then the tool_use blocks.
  • Streamed Messages replies: a thinking block of thinking_delta pieces. It starts with an empty signature, the
    same shape as a whole reply's block, and stops after an empty signature_delta, which the API requires before a
    thinking block stops. Then comes the text block, and the
    tool_use blocks take the indexes after.
    • Each block starts with its first piece and stops before the next starts.
    • A </think> split over two pieces waits for the second, as on the OpenAI path.
  • thinking: {"type": "disabled"} maps to enable_thinking: false; enabled with budget_tokens works as before.
  • Non-streamed OpenAI replies with tool calls get reasoning_content and a clean content (second commit, which
    can be dropped on its own).
  • split_think replaces the inline split of the non-streamed OpenAI reply; behaviour there is unchanged.

Without a think block (thinking off, or a model without one), the output is the same as before: one text block.

Before / after

POST /v1/messages, "What is 17*23? Answer with the number only.", Qwen3.6-35B-A3B, thinking on (server default):

before: [{"type": "text", "text": "Here's a thinking process ... Output: 391.\n</think>\n\n391"}]
after:  [{"type": "thinking", "thinking": "Here's a thinking process ... (1062 chars)", "signature": ""}, {"type": "text", "text": "391"}]

Tests

  • New unit tests, all passing:
    • messages_api_tests (main.rs), which checks the exact event sequence of a stream:
      • streamed_reasoning_is_a_thinking_block_before_the_text
      • streamed_reply_without_think_block_is_one_text_block
      • reasoning_cut_off_by_max_tokens_still_stops_its_block
      • whole_reply_puts_reasoning_in_a_thinking_block
    • serve::messages_tests::thinking_turns_thinking_on_and_off
    • The existing messages_api_request passes too.
  • Full suite: cargo test --release in a container with NVRTC 12.4 and no GPU, so the GPU and model tests skip themselves.
    It gives 429 passed, 0 failed, 11 ignored (upstream's #[ignore] speed tests).
  • Live checks, against a server running this branch together with CUDA: CUDA-core FMA path for GTX 16 (Turing without tensor cores) #134 (GTX 1660 SUPER, Qwen3.6-35B-A3B UD-Q2_K_XL):
    • /v1/messages, whole: [thinking (1062 chars, signature ""), text "391"], end_turn, no </think> in the text.
    • /v1/messages, streamed: message_start, start 0 thinking, thinking_delta…, signature_delta, stop 0,
      start 1 text, text_delta…, stop 1, message_delta, message_stop.
    • thinking: {"type": "disabled"}: [text "391"], no thinking block.
    • With a tool, whole: [thinking, tool_use read_file], stop_reason: tool_use.
    • With a tool, streamed: thinking block 0, then tool_use block 1 (input_json_delta).
    • /v1/chat/completions with a tool, whole: tool_calls [read_file], reasoning_content 128 chars, content empty
      (before: the reasoning and </think> in content).
    • Open WebUI (/v1/chat/completions, streamed) unchanged.

@aletheore

aletheore Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/serve.rs"]
    n1["src/chat.rs"]
    n2["src/deepseek/chat.rs"]
    n3["src/gemma4/mod.rs"]
    n4["src/glm/mod.rs"]
    n5["grammar.rs"]
    n6["hf.rs"]
    n7["src/hy4/chat.rs"]
    n8["src/inkling2/chat.rs"]
    n9["src/kolibri/chat.rs"]
    n10["lib.rs"]
    n11["src/raon/chat.rs"]
    n12["tests/serve.rs"]
    n13["tokenizer.rs"]
    n0 --> n1
    n0 --> n2
    n0 --> n3
    n0 --> n4
    n0 --> n5
    n0 --> n6
    n0 --> n7
    n0 --> n8
    n0 --> n9
    n0 --> n10
    n0 --> n11
    n0 --> n12
    n0 --> n13
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 dependent
    class n2 dependent
    class n3 dependent
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • docs/USAGE.md · modified · +4/-1
  • src/main.rs · modified · +144/-17 · +13 functions, -1 function, +1 class
  • src/serve.rs · modified · +29/-5 · +1 function · 13 other dependents

Aggregate deltas

  • Modules: +0
  • Dependency graph edges: +0
  • Commits: 3

Comment thread src/main.rs Outdated
if t.is_empty() { return Ok(()); }
if self.open != Some(thinking) {
self.close(w)?;
let block = if thinking { json!({"type": "thinking", "thinking": ""}) } else { json!({"type": "text", "text": ""}) };

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of c2db2f5e7b1c.


🟠 High · Correctness · 1 of 4

Thinking content_block_start omits the signature field that the non-streaming thinking block includes. The non-streaming path emits a thinking block with "signature": "", but the streaming content_block_start emits {"type":"thinking","thinking":""}. A strict Anthropic-style client that builds the block from the start event and then sees signature_delta may hit a missing-field error or assemble a different shape than the non-streaming reply.

Prompt for your AI agent
File: src/main.rs
Line: 3964
Symbol: handle
Issue: Thinking content_block_start omits the signature field that the non-streaming thinking block includes. The non-streaming path emits a thinking block with "signature": "", but the streaming content_block_start emits {"type":"thinking","thinking":""}. A strict Anthropic-style client that builds the block from the start event and then sees signature_delta may hit a missing-field error or assemble a different shape than the non-streaming reply.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dab867e. A streamed thinking block now starts with "signature": "", the same shape as a whole reply's block, and the signature_delta still comes before it stops. The stream test checks the start block.

Comment thread src/main.rs
self.send(w, p)
}
/// Sends `rest` and what the splitter still holds, then stops the open block.
fn finish(&mut self, w: &mut impl Write, rest: &str) -> anyhow::Result<()> {

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of dab867ec231d.


🔵 Low · Maintainability · 2 of 4

AnthStream::finish re-implements the split_think feed/finish sequence instead of reusing it. The Think feed-then-finish sequence now lives in split_think, in AnthStream::finish, and in AnthStream::feed/send. A later change to how Think flushes held text (for example a partial </think> at end of stream) must be made in several places, and one copy can drift from the others.

Prompt for your AI agent
File: src/main.rs
Line: 3949
Symbol: handle
Issue: AnthStream::finish re-implements the split_think feed/finish sequence instead of reusing it. The Think feed-then-finish sequence now lives in split_think, in AnthStream::finish, and in AnthStream::feed/send. A later change to how Think flushes held text (for example a partial </think> at end of stream) must be made in several places, and one copy can drift from the others.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dab867e: finish now calls feed, then flushes the splitter.

Comment thread src/main.rs Outdated
if stream { return json!({"tool_calls": c}); }
// The text before the calls opens with the reasoning when the prompt ended in an open think block.
let (r, a) = split_think(think_open, content);
let mut m = json!({"role": "assistant", "content": if a.is_empty() { None } else { Some(a) }, "tool_calls": c});

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of c2db2f5e7b1c.


🔵 Low · Maintainability · 3 of 4

Early return inside the calls_json branch makes the tool-call message shape hard to follow. The stream and non-stream outcomes are built in one expression with a return on one arm and a trailing expression on the other. A reader or a later edit can miss that the streamed tool-call message silently drops reasoning, and a change to the non-stream fields may not reach the streamed path.

Prompt for your AI agent
File: src/main.rs
Line: 4342
Issue: Early return inside the calls_json branch makes the tool-call message shape hard to follow. The stream and non-stream outcomes are built in one expression with a return on one arm and a trailing expression on the other. A reader or a later edit can miss that the streamed tool-call message silently drops reasoning, and a change to the non-stream fields may not reach the streamed path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restructured in dab867e as one if/else. On the streamed path the reasoning isn't dropped, though: it goes out earlier, as reasoning_content deltas before the tool-call deltas.

Comment thread src/main.rs
/// has none to give), then the answer as a `text` block, then the tool calls.
fn anthropic_content(reasoning: &str, text: &str, uses: Vec<serde_json::Value>) -> Vec<serde_json::Value> {
let thinking = (!reasoning.is_empty()).then(|| json!({"type": "thinking", "thinking": reasoning, "signature": ""}));
let text = (!text.is_empty()).then(|| json!({"type": "text", "text": text}));

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of dab867ec231d.


🟡 Medium · Correctness · 4 of 4

Non-streaming reply with reasoning but no text or tool calls returns only a thinking block. A reply that is all reasoning (for example one cut off by max_tokens before </think>) yields content with only a thinking block. Clients that read content[0].text, or expect a text block as the final answer, get nothing usable and may treat the reply as empty.

Prompt for your AI agent
File: src/main.rs
Line: 3932
Symbol: anthropic_refused
Issue: Non-streaming reply with reasoning but no text or tool calls returns only a thinking block. A reply that is all reasoning (for example one cut off by max_tokens before </think>) yields content with only a thinking block. Clients that read content[0].text, or expect a text block as the final answer, get nothing usable and may treat the reply as empty.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/dismiss By design. A reply cut off by max_tokens inside the reasoning has no answer, and the Messages API says exactly that: a thinking block alone, with stop_reason: "max_tokens". Anthropic's API does the same, and llama.cpp's server builds the same blocks. An empty text block would be a shape the API never sends.

@aletheore

aletheore Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR returns the model's reasoning separately from its answer: as thinking content blocks on the Messages API (streamed and whole) and as reasoning_content on chat completions, including replies that end in tool calls. It also lets Messages API clients turn thinking off, adds a llama.cpp-style /props endpoint, and changes the over-long-prompt error to the wording that agents like Pi use to trigger compaction.

Merge confidence Review effort Merge risk
3 / 5 3 / 5 Medium
Area Files Lines
src 2 +202 −23
docs 1 +25 −2

1 finding(s) posted as inline review comment(s). 4 earlier finding(s) no longer detected in this push.

# Severity Category Where
1 🟠 High Correctness serve.rs:946 thinking disabled sets enable_thinking false, but the model still writes a short think block, which then…
Review details

Reviewed 3 file(s); skipped 0. Dismissed 0; outside PR diff 2. Grounding: 3 of 3 proposed finding(s).

Fix all with your agent
File: src/serve.rs
Line: 946
Symbol: messages_body
Issue: thinking disabled sets enable_thinking false, but the model still writes a short think block, which then leaks into the answer The docs say Inkling 2 still writes a short thinking block at effort 0, even with enable_thinking false. A Messages request with thinking {"type":"disabled"} therefore gets a reply that opens with reasoning and a literal </think>. The caller builds Think::new(think_open) with think_open false, so nothing is split: the reasoning and the tag land in the text block. That is the leak this PR is meant to fix, and it returns for exactly the requests that asked to turn thinking off.
Make the smallest change that fixes this, add a test, and change nothing unrelated.
Blast radius: 63 other file(s) depend on what this PR changes (13 directly, 50 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/serve.rs is imported by src/chat.rs, src/deepseek/chat.rs, src/gemma4/mod.rs, src/glm/mod.rs (+9 more)

Indirectly affected: src/backend.rs, src/calibrate.rs, src/config.rs, src/cpu_moe.rs, src/cpu_worker.rs, src/cuda/mod.rs (+44 more)

The graph is large; this list is capped and not exhaustive.

PedroRossi added a commit to PedroRossi/RustingStrata that referenced this pull request Nov 27, 2026
/v1/messages sent the whole generated text as one text block, so a thinking model's
reasoning and its </think> tag reached the client as the answer (Claude Code shows
it in every reply). It now goes through the same splitter as /v1/chat/completions:
- a whole reply: a thinking block (empty signature), then the text block, then the
  tool_use blocks;
- a stream: a thinking block of thinking_delta pieces that stops after an empty
  signature_delta, then the text block; the tool_use blocks take the indexes after.
thinking: {"type": "disabled"} now turns thinking off for the request; before, the
server default applied. Tests for the stream events, the whole-reply blocks and the
request mapping.
A non-streamed /v1/chat/completions reply with tool calls put the text before the
calls in content as it was, reasoning and </think> included, with no
reasoning_content. It now splits that text like a reply without calls. Streamed
replies already split it.
- A streamed thinking block starts with an empty signature, the same shape as a
  whole reply's block (the signature_delta still comes before it stops); tested.
- AnthStream::finish reuses feed instead of repeating it.
- The tool-call message is one if/else: a stream's tool calls, or a whole reply's
  message with reasoning_content. No change in behaviour.
Comment thread src/main.rs
b.finish(&mut out, "").unwrap();
assert_eq!(events(&out), ["start 0 thinking", r#"0 thinking "Let me""#, r#"0 thinking " think.\n""#, r#"0 signature_delta """#,
"stop 0", "start 1 text", r#"1 text "The answer""#, r#"1 text " is 4.""#, "stop 1"]);
assert_eq!(b.next, 2); // a tool call would be block 2

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of dab867ec231d.


🔵 Low · Maintainability · 1 of 2

The new test reads the first data: line, which is probably message_start, not the thinking content_block_start. The stream begins with message_start, so find_map returns that event. Its content_block is null and the assertion fails even when the thinking block is correct. The test should select the content_block_start event for index 0, or the thinking block's event, by its type field.

Prompt for your AI agent
File: src/main.rs
Line: 4432
Symbol: vram_margins_reject_bad_specs
Issue: The new test reads the first `data:` line, which is probably message_start, not the thinking content_block_start. The stream begins with message_start, so `find_map` returns that event. Its `content_block` is null and the assertion fails even when the thinking block is correct. The test should select the content_block_start event for index 0, or the thinking block's event, by its `type` field.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/main.rs
else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) }
if stream {
// A stream sent the reasoning already, as `reasoning_content` deltas before the calls.
json!({"tool_calls": c})

@aletheore aletheore Bot Nov 27, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No longer detected as of dab867ec231d.


🔵 Low · Correctness · 2 of 2

The streaming tool-call branch relies on reasoning already having been sent as reasoning_content deltas, which the diff does not show. If the streaming path does not emit reasoning_content deltas before tool calls, the reasoning is dropped for streamed tool-call replies, while the non-streamed branch still returns it. The stream and non-stream outputs would then differ silently.

Prompt for your AI agent
File: src/main.rs
Line: 4341
Issue: The streaming tool-call branch relies on reasoning already having been sent as reasoning_content deltas, which the diff does not show. If the streaming path does not emit reasoning_content deltas before tool calls, the reasoning is dropped for streamed tool-call replies, while the non-streamed branch still returns it. The stream and non-stream outputs would then differ silently.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@PedroRossi
PedroRossi force-pushed the pr/anthropic-thinking-blocks branch from c2db2f5 to dab867e Compare November 27, 2026 23:04
PedroRossi added a commit to PedroRossi/RustingStrata that referenced this pull request Nov 27, 2026
…ustingStudio#135 (Messages API thinking blocks)

Integration branch for the ai-lab stack image; not for upstream.
Comment thread src/serve.rs
out.push(("thinking_budget", j.get("thinking").get("budget_tokens").clone()));
match j.get("thinking").get("type").as_str() {
Some("enabled") => {
out.push(("chat_template_kwargs", obj(vec![("enable_thinking", Json::Bool(true))])));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 1

thinking disabled sets enable_thinking false, but the model still writes a short think block, which then leaks into the answer The docs say Inkling 2 still writes a short thinking block at effort 0, even with enable_thinking false. A Messages request with thinking {"type":"disabled"} therefore gets a reply that opens with reasoning and a literal </think>. The caller builds Think::new(think_open) with think_open false, so nothing is split: the reasoning and the tag land in the text block. That is the leak this PR is meant to fix, and it returns for exactly the requests that asked to turn thinking off.

Prompt for your AI agent
File: src/serve.rs
Line: 946
Symbol: messages_body
Issue: thinking disabled sets enable_thinking false, but the model still writes a short think block, which then leaks into the answer The docs say Inkling 2 still writes a short thinking block at effort 0, even with enable_thinking false. A Messages request with thinking {"type":"disabled"} therefore gets a reply that opens with reasoning and a literal </think>. The caller builds Think::new(think_open) with think_open false, so nothing is split: the reasoning and the tag land in the text block. That is the leak this PR is meant to fix, and it returns for exactly the requests that asked to turn thinking off.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant